from django.http import HttpResponse, JsonResponse
from django.utils.deprecation import MiddlewareMixin
from rest_framework import status


class SessionMiddleware(MiddlewareMixin):
    """自定义请求中间件"""

    def process_request(self, request):
        """请求时处理函数"""
        # print("###收到请求...", request.method, request.path)
        # if request.path.find("/api/EditToken/") > -1:
        #     if request.method == "PATCH":
        #         print(dir(request))
        #         print(request.META)
        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        """视图处理函数"""
        # traceback.print_exc()
        # print("###载入视图...", request.method, request.path)

        return None

    # def process_exception(self, request, exception):
    #     """发生错误时处理函数"""
    #     # print("###系统错误...", request.method, request.path)
    #     # print("###错误消息...", exception)
    #     print(
    #         f"\033[1;31m Middle-Error:{request.method} {request.path} \n {exception} \033[0m"
    #     )
    #     ex_data = {
    #         "msg": "Sorry, we make a mistake (*￣︶￣)!",
    #         "error_code": 500,
    #         "method": request.method,
    #         "request": request.path,
    #     }
    #     return JsonResponse(data=ex_data, status=500)

    def process_response(self, request, response):
        """直接返回处理函数"""
        # print("###直接返回...", request.method, request.path, response.status_code)
        # response["Access-Control-Allow-Origin"] = "*"  # 支持跨域,允许所有域名访问
        # response["Access-Control-Allow-Headers"] = "Content-Type"  # 允许的请求类型
        # response[
        #     "Access-Control-Allow-Methods"
        # ] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"  # 允许的客户端访问方法
        # response["Access-Control-Max-Age"] = 86400  # 预检有效时间为 86400 秒24小时
        return response

    def process_template_response(self, request, response):
        """模板返回处理函数"""
        # print("###模板返回...", request.method, request.path, response.status_code)
        # print(response.data)
        # 处理反序列化字段唯一错误
        # if not response.status_code == 200:
        #     print(
        #         f"\033[1;33m Middle-Res:{request.method} {request.path} \n {response.data} \033[0m"
        #     )
        #     response.data = {
        #         "rescode": response.status_code,
        #         "resmsg": f"{response.data}",
        #     }

        # response.status = status.HTTP_200_OK
        # response.status_code = 200
        return response
